const express = require('express')
const router = express.Router()
const models = require('../models')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const {success, error} = require('../utils/message')

// 前台注册
router.post('/sign_up', async function (req, res, next) {
    const username = req.body.username
    const password = req.body.password
    const mobile = req.body.mobile
    const avatar = req.body.avatar

    if (!(username)) {
        return error(res, '用户名必须填写！')
    }

    if (username.length < 5) {
        return error(res, '用户名不能少于5位字符！')
    }

    if (!(password)) {
        return error(res, '密码必须填写！')
    }

    if (!(mobile)) {
        return error(res, '手机号必须填写！')
    }

    const phone = /^(0|86|17951)?(13[0-9]|15[012356789]|16[6]|19[89]]|17[01345678]|18[0-9]|14[579])[0-9]{8}$/
    const st = new RegExp(phone)
    if (!st.test(mobile)) {
        return error(res, '请填写正确的 11 位手机号！')
    }

    if (!(avatar)) {
        return error(res, '请上传头像！')
    }

    let user = await models.User.findOne({where: {username: username}})
    if (user) {
        return error(res, '用户名已经存在，请直接登录！')
    }

    // 生成盐
    const salt = bcrypt.genSaltSync(10)

    // 对用户填写的密码进行加密
    const hash = bcrypt.hashSync(password.toString(), salt)

    // 用户数据
    const body = {
        username: username,
        password: hash,
        admin: false,
        mobile: mobile,
        avatar: avatar
    }

    user = await models.User.create(body)
    return success(res, '注册成功', {user})
})

// 前台登录
router.post('/sign_in', async function (req, res, next) {
    const username = req.body.username
    const password = req.body.password

    if (!(username)) {
        return error(res, '用户名必须填写！')
    }

    if (!(password)) {
        return error(res, '密码必须填写！')
    }

    // 查询用户信息
    const user = await models.User.findOne({
        where: {
            username: username,
        },
    })

    // 用户是否存在
    if (!user) {
        return error(res, '用户名不存在！')
    }

    // 验证密码
    if (!bcrypt.compareSync(password, user.password)) {
        return error(res, '用户名或密码错误！')
    }

    // 生成token，返回出去
    const token = jwt.sign({
        user: {
            id: user.id,
            username: user.username,
            admin: user.admin
        }
    }, process.env.SECRET, { expiresIn: 60 * 60 * 24 * 7 })

    return success(res, '登录成功', { token })
})


module.exports = router
